package com.behome.netty.netty_A.server;

import com.behome.netty.common.ByteConventerKit;
import com.behome.netty.common.DecodeResult;
import com.behome.netty.netty_A.bean.ProtocolAPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.*;

/**
 * 应急广播国标附录A解析器
 */
@Slf4j
public class StandardADecoder extends ByteToMessageDecoder {
    final int MIN_LENGTH = 15;
    final byte HEAD_FLAG = 80;
    final int HEAD_LENGTH = 9;
    final int TAIL_MIN_LENGTH = 6;
    final int INDEX_BODY_LENGTH = 5;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) {
        try{
            in.markReaderIndex();
            byte[] buffer = new byte[in.readableBytes()];
            in.readBytes(buffer);
            Map<String, byte[]> map = new HashMap<>();
            map.put("data", buffer);
            boolean rightDecoder = false;
            List<Object> obj = new ArrayList<>();
            try {
                DecodeResult decodeResult =  decode(map,obj);
                if(null != decodeResult && !decodeResult.isSuccess()) {
                    rightDecoder = decodeResult.isRightDecoder();
                }
            } catch (Exception var12) {
                String msg = "对" + ctx.channel().remoteAddress().toString() + "发来的数据[" + ByteConventerKit.bytesToHexStr(buffer, false) + "]解析时发生错误.";
                log.error(msg, var12);
            }
            if(!obj.isEmpty()) {
                list.addAll(obj);
            }
            if(rightDecoder && map.containsKey("data") && map.get("data").length > 0) {
                int readerIndex = buffer.length - map.get("data").length;
                if(readerIndex >= 0) {
                    in.readerIndex(readerIndex);
                }
            }
        }catch (Exception e){
            log.error("附录A解析异常："+ Arrays.toString(e.getStackTrace()));
            throw e;
        }
    }

    public DecodeResult decode(Map<String, byte[]> bufferMap, List<Object> returnObjs) {
        String dataStr="data";
        if(!bufferMap.containsKey(dataStr)) {
            return null;
        } else if(((byte[])bufferMap.get(dataStr))[0] != HEAD_FLAG) {
            return new DecodeResult(false, false);
        } else if(bufferMap.get(dataStr).length <= MIN_LENGTH) {
            return null;
        } else {
            ByteBuffer byteBuffer = ByteBuffer.wrap(bufferMap.get(dataStr)).asReadOnlyBuffer();
            int bodyLength = byteBuffer.getInt(INDEX_BODY_LENGTH);
            //头信息9个 +18个消息体
            int indexSignature = HEAD_LENGTH + bodyLength;
            if(byteBuffer.remaining() - indexSignature <= 2) {
                if(indexSignature>50000){
                    bufferMap.remove(dataStr);
                }
                log.warn("长度不够一个包，下一周期处理");
                return new DecodeResult(false, true);
            } else {
                short signatureLength;
                try{
                    signatureLength = byteBuffer.getShort(indexSignature);
                }catch (Exception e){
                    return new DecodeResult(false, true);
                }
                int packetLength = HEAD_LENGTH + bodyLength + TAIL_MIN_LENGTH + signatureLength;
                if(byteBuffer.remaining() < packetLength) {
                    log.warn("长度不够一个包，下一周期处理");
                    return new DecodeResult(false, true);
                } else {
                    byte[] data = new byte[packetLength];
                    byteBuffer.get(data, 0, data.length);
                    ProtocolAPacket packet = ProtocolAPacket.deserialize(data);
                    if(returnObjs == null) {
                        returnObjs = new ArrayList<>();
                    }
                    if(packet != null) {
                        returnObjs.add(packet);
                    }
                    if(byteBuffer.hasRemaining()) {
                        byte[] remainData = new byte[byteBuffer.remaining()];
                        byteBuffer.get(remainData);
                        bufferMap.put(dataStr, remainData);
                        this.decode(bufferMap, returnObjs);
                    } else {
                        bufferMap.remove(dataStr);
                    }
                    return new DecodeResult(true, true);
                }
            }
        }
    }
}
